﻿import QtQuick 2.6
import QtQuick.Window 2.2
import QtWebEngine 1.10
import QtQuick.Controls.Styles 1.0
import QtQuick.Controls 1.4
import HistoryManager 1.0
import BookmarkManager 1.0
import DownloadManager 1.0
import QtQuick.Controls 2.14
import QtQuick.Layouts 1.14
import User 1.0
import "../js/MyTool.js" as MyTool
import "../component/"

Window {
    id: window
    visible: true
    width: 960
    height: 720
    title: "隆中对浏览器"
    minimumWidth: 900
    minimumHeight: 500

    property alias mainWindow : window

    flags: Qt.Window | Qt.FramelessWindowHint

    ResizeItem {
        enableSize: 8
        anchors.fill: parent
        focus: true
        TitleBar{
            id:titleBar
            anchors{left: parent.left;right: parent.right; top: parent.top;}
            height: 40

        }


        //地址栏及一众按钮
        Rectangle {
            id: row_line_2
            height: 50
            anchors.top: titleBar.bottom

            anchors.right: parent.right
            anchors.rightMargin: 0
            anchors.left: parent.left
            anchors.leftMargin: 0
            color:"#DDDFE2"

            //地址栏左侧
            Row {
                id: row_line_2_left
                height: 40
                spacing: 16
                anchors.left: parent.left
                anchors.leftMargin: 20
                anchors.verticalCenter: parent.verticalCenter
                //后退
                MyButton{
                    id: image
                    icon_default:"../../src/arrow_left.png"
                    icon_disabled: "../../src/arrow_left_disabled.png"

                    enabled:currentWebView && currentWebView.canGoBack
                    onClicked:{
                        if(currentWebView && currentWebView.canGoBack){
                            currentWebView.goBack()
                        }else{
                            console.log("返回失败")
                        }
                    }
                }

                //前进
                MyButton{
                    id: image1
                    icon_default:"../../src/arrow_right.png"
                    icon_disabled: "../../src/arrow_right_disabled.png"

                    enabled:currentWebView && currentWebView.canGoForward
                    onClicked:{
                        if(currentWebView && currentWebView.canGoForward){
                            currentWebView.goForward()
                        }else{
                            console.log("前进失败")
                        }
                    }
                }
                //主页
                MyButton{
                    id: image2
                    icon_default:"../../src/home.png"
                    m_padding: 4
                    onClicked:{
                        //主页效果待完善
                        currentWebView.url="https://www.baidu.com"
                    }
                }
                //刷新
                MyButton{
                    id: image3
                    icon_default:"../../src/refresh.png"
                    icon_disabled: "../../src/refresh_disabled.png"
                    enabled: currentWebView && !currentWebView.loading
                    m_padding: 4
                    onClicked:{
                        //或许可以完善
                        currentWebView.reload()
                    }
                }
            }

            //地址栏
            Rectangle{
                id: textInput_line
                anchors.right: row_line_2_right.left
                anchors.rightMargin: 20
                anchors.left: row_line_2_left.right
                anchors.leftMargin: 20
                height: 40
                radius: 5
                color: "white"
                anchors.verticalCenter: parent.verticalCenter
                property var num: 1


                TextInput {
                    id: textInput
                    activeFocusOnPress: true
                    cursorDelegate: cursor

                    color: "#747474"
                    selectionColor: "#0078d4"
                    selectByMouse: true
                    cursorVisible: false

                    anchors.top: parent.top
                    anchors.topMargin: 5
                    anchors.bottom: parent.bottom
                    anchors.bottomMargin: 4
                    anchors.left: parent.left
                    anchors.leftMargin: 10
                    anchors.right: parent.right
                    anchors.rightMargin: 10

                    clip:true

                    layer.textureSize.width: 1
                    font.pixelSize: 22
                    font.family:"微软雅黑"

                    text: currentWebView.url

                    //enter按钮点下，自动更改页面
                    onAccepted: {
                        currentWebView.url=textInput.text

                    }

                }

                Component{
                    id:cursor

                    Rectangle{
                        id:cursorRect
                        width: 2
                        height: 40
                        color: (textInput_line.num == 1) ? "black" : "white"
                    }

                }
                Timer{
                    interval: 500;
                    repeat: true;
                    running: true
                    onTriggered: {
                        textInput_line.num = (textInput_line.num == 1) ? 0 : 1
                    }
                }
            }

            //右侧
            Row {
                id: row_line_2_right
                height: 40
                anchors.verticalCenter: parent.verticalCenter
                spacing: 16
                anchors.right: parent.right
                anchors.rightMargin: 20
                //收藏
                MyButton{
                    id: image4
                    icon_default:flag?"../../src/collect_fill.png":"../../src/collect.png"
                    m_padding: 4
                    property var flag:false
                    onClicked:{
                        console.log("collect clicked")
                        //取消收藏
                        let webUrl=JSON.parse(JSON.stringify(currentWebView.url))
                        console.log(webUrl)
                        if(flag){
                            if(bookmarkManager.isFavorited(webUrl)){
                                bookmarkManager.remove(webUrl)
                                flag=false
                            }
                        }//添加收藏
                        else{
                            if(!bookmarkManager.isFavorited(webUrl)){
                                bookmarkManager.add(webUrl,MyTool.getWebIcoUrl(webUrl),currentWebView.title)
                                flag=true
                            }

                        }
                    }
                    function update(url){
                        flag=bookmarkManager.isFavorited(url)
                    }

                }
                //历史记录
                MyButton{
                    id: image5
                    icon_default:"../../src/history.png"
                    m_padding: 4
                    onClicked:{
                        console.log("history clicked")

                        drawer3.open()
                    }
                }
                //收藏夹
                MyButton{
                    id: image6
                    icon_default:"../../src/folder.png"
                    m_padding: 4

                    onClicked:{
                        console.log("folder clicked")
                        drawer4.open()
                    }
                }
                //下载列表
                MyButton{
                    id: image7
                    icon_default:"../../src/download.png"
                    m_padding: 4
                    onClicked:{
                        console.log("download clicked")
                        downloadView.visible = !downloadView.visible;
                    }
                }
                //用户登录
                MyButton{
                    id: image8
                    icon_default:"../../src/user.png"
                    m_padding: 4
                    onClicked:{
                        userview.visible = true
                        console.log("user clicked")
                        //                    user1.logout()
                    }
                }
                //设置
                MyButton{
                    id: image9
                    icon_default:"../../src/setting.png"
                    m_padding: 4
                    onClicked:{
                        console.log("setting clicked")
                        drawer.toggle()

                        console.log("c++ test",adblockProfile.httpUserAgent)

                    }
                }
            }

        }

        //下面的tabview
        TabView {
            id: tabs
            anchors.top: row_line_2.bottom
            anchors.right: parent.right
            anchors.rightMargin: 0
            anchors.left: parent.left
            anchors.leftMargin: 0
            anchors.bottom: parent.bottom
            anchors.bottomMargin: 0

            property var iconList: []
            signal iconChange
            //设置tab项的icon相关
            function addIconList(icon){
                if(icon===undefined){
                    icon="../../src/icon_default.png"
                }
                iconList.push(icon)
            }
            function changeIconList(index,icon){
                iconList[index]=icon
                console.log(iconList)
                iconChange()
            }
            function deleteIconList(index){
                if(iconList.length>1){
                    iconList.splice(index,1)
                }else{
                    console.log("delete falied")
                }
            }

            //创建新的tabbar，里面新增webview
            function createEmptyTab() {
                //todo:profile
                var tab = addTab("", tabComponent);
                tab.active = true;
                tab.title = Qt.binding(function() { return tab.item.title ? tab.item.title : 'New Tab' });
                tabs.addIconList()
                return tab;
            }
            //获取当前的webview的index
            function indexOfView(view) {
                for (let i = 0; i < tabs.count; ++i)
                    if (tabs.getTab(i).item === view)
                        return i
                return -1
            }
            //移除webview
            function removeView(index) {
                if (tabs.count > 1){
                    tabs.removeTab(index)
                    tabs.deleteIconList(index)
                }
                else
                    window.close();
            }
            //首次运行时调用
            Component.onCompleted: createEmptyTab()
            //重写tabbar样式
            style: TabViewStyle {
                property color frameColor: "#DDDFE2"
                property color fillColor: "#DDDFE2"
                property color nonSelectedColor: "#AAB0B6"

                tabBar:Rectangle{
                    color: nonSelectedColor

                }
                leftCorner:Rectangle{
                    implicitWidth: 20
                    implicitHeight: 36
                    color: nonSelectedColor
                }
                //右边的加号创建新tab
                rightCorner:Rectangle{
                    implicitWidth: 60
                    implicitHeight: 36
                    color: fillColor
                    MyButton{
                        anchors.fill: parent
                        anchors.centerIn: parent
                        m_padding: 2
                        m_radius: 0
                        icon_default: "../../src/add.png"
                        onClicked: {
                            var newTab = tabs.createEmptyTab()
                        }
                    }
                }

                //重写tab样式
                tab:Rectangle {
                    id: tabRectangle
                    implicitHeight: 36
                    width: 300;
                    color: styleData.selected ? fillColor : nonSelectedColor
                    border.width: 1
                    border.color: frameColor
                    implicitWidth: tabRow.width
                    Row{
                        id:tabRow
                        spacing: 10
                        leftPadding: 10
                        rightPadding: 10
                        anchors.centerIn: parent
                        MyIcon{
                            id:icon1
                            width: 20
                            height: 20
                            anchors.verticalCenter: parent.verticalCenter
                            icon:"../../src/icon_default.png"
                            Connections {
                                target: tabs; // 表示发出信号的对象
                                function onIconChange(){
                                    icon1.icon=tabs.iconList[styleData.index]?tabs.iconList[styleData.index]:"../../src/icon_default.png"
                                }
                            }
                        }
                        Text {
                            id: label
                            text: styleData.title
                            elide:Text.ElideRight
                            anchors.verticalCenter: parent.verticalCenter
                            onContentWidthChanged: {
                                label.width=Math.min(label.contentWidth+20,210)
                            }
                        }
                        //删除当前tab的按钮
                        MyButton{
                            id:icon2
                            width: 30
                            height: 24
                            m_padding: 3
                            anchors.verticalCenter: parent.verticalCenter

                            icon_default: "../../src/delete.png"
                            onClicked: {
                                tabs.removeView(styleData.index)
                            }
                        }

                    }


                }
            }

            //里面包含webview
            Component{
                id:tabComponent
                WebEngineView {
                    id: webView
                    anchors {
                        top: parent.top
                        left: parent.left
                        right: parent.right
                        bottom: parent.bottom
                        margins: 1
                    }
                    //默认url为百度
                    url: "https://www.baidu.com"
                    smooth: true
                    visible: true
                    profile:  webProfile

                    //地址改变时自动调用（注意和oniconchanged调用时间不一定一样，可能得加判断）
                    onUrlChanged: {
                        textInput.text=webView.url
                        image4.update(webView.url)
                    }
                    //此处获取icon
                    onIconChanged: {
                        if(webView.icon!==null){
                            var index=tabs.indexOfView(webView)
                            tabs.changeIconList(index,webView.icon)
                        }
                    }
                    //此处进行添加历史记录的操作
                    onLoadingChanged: {
                        if(loadRequest.status===WebEngineLoadRequest.LoadSucceededStatus){
                            var list2=historyManager.getHistoryItemList()
                            console.log("qml history length:",list2.length)

                            var webUrl=JSON.parse(JSON.stringify(webView.url))
                            if(webView.title===""||webView.title===undefined||webUrl===""){
                                console.log("continue")
                            }else{
                                let iconUrl=MyTool.getWebIcoUrl(webUrl)
                                if(iconUrl===""){
                                    console.log("continue")
                                }else{
                                    console.log("history add")
                                    historyManager.add(webUrl,iconUrl,webView.title,new Date())
                                    console.log("url:",webUrl,"title:",webView.title,"icon:",iconUrl)
                                }
                            }
                        }else{
                            console.log("loadingchange")
                        }
                    }


                    //这里是判断要不要新加tab，还是直接原界面打开
                    onNewViewRequested: function(request) {
                        console.log("new tab view")
                        if (!request.userInitiated)
                            print("Warning: Blocked a popup window.");
                        else if (request.destination === WebEngineView.NewViewInTab) {
                            var tab = tabs.createEmptyTab();
                            tabs.currentIndex = tabs.count - 1;
                            request.openIn(tab.item);
                        }else{
                            console.log("其他")
                        }
                    }
                }
            }

            //tabindex更改时自动调用
            onCurrentIndexChanged:{
                //页面tab切换逻辑
                textInput.text=tabs.getTab(currentIndex).item.url
                image4.update(textInput.text)

            }

        }

        //下载展示的窗口（小）
        DownloadView{
            id:downloadView
            z:2
            anchors.right: parent.right
            anchors.rightMargin: 140
            anchors.top: row_line_2.bottom
            anchors.topMargin: 2
            border.color: "black"
            border.width: 1
            visible: false
            btnClicked:function(){
                console.log("show history")
                downloadView.visible=false
                drawer2.toggle()
            }
        }

    }





    property Item currentWebView: tabs.currentIndex < tabs.count ? tabs.getTab(tabs.currentIndex).item : null
    //设置profile 关于下载地址相关等
    property QtObject defaultProfile: WebEngineProfile {
        storageName: "Profile"
        offTheRecord: false
        useForGlobalCertificateVerification: true
        downloadPath: downloadManager.path
        cachePath:downloadManager.path

        httpUserAgent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"

        onDownloadRequested: {
            downloadView.visible = true;
            downloadView.append(download);
            console.log("download start")
            download.accept();
        }
        onDownloadFinished: {
            if (download.state === 2){
                console.log("download finish")
                downloadManager.add(download.downloadDirectory,download.downloadFileName,new Date())

            }
        }
    }
    //adblock 相关设置
    WebEngineProfile{
        id:tempProfile
        objectName: "adblockProfile"
        storageName: "Profile"
        offTheRecord: false
        useForGlobalCertificateVerification: true
        downloadPath: downloadManager.path
        cachePath: downloadManager.path

        httpUserAgent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"

        onDownloadRequested: {
            downloadView.visible = true;
            downloadView.append(download);
            console.log("download start")
            download.accept();
        }
        onDownloadFinished: {
            if (download.state === 2){
                console.log("download finish")
                downloadManager.add(download.downloadDirectory,download.downloadFileName,new Date())

            }
        }
    }

    property QtObject webProfile: adBlockSwitch.checked && (typeof(adblockProfile) !== "undefined") ? adblockProfile : window.defaultProfile
    //有notify自动更新，可以通过这两个对象进行操作
    property HistoryManager historyManager: user1.historyManager
    property BookmarkManager bookmarkManager: user1.bookmarkManager
    property DownloadManager downloadManager: user1.downloadManager

//    DownloadManager{
//        id:downloadManager
//    }

    User{
        id:user1
        onSendMsg: {
            msg(str)
        }
        //消息槽
        function msg(str){
            console.log("????????"+str + "!!!!!!!!!!")
        }
        onUserChanged: {
            //编写user改变的逻辑
            console.log("user change")

            image4.update(currentWebView.url)

        }
        Component.onCompleted: {
            console.log("=======================")
            createUser("josefu","123456")
        }
    }

    //测试userview
    UserView{
        id:userview
        visible: false
    }

    //这里可以调用测试c++代码
    Component.onCompleted: function(){
        mainWindow.show()
        window.showMaximized()


    }


    //下载展示的窗口（大）
    Drawer{
        id:drawer2
        edge: Qt.RightEdge
        height: window.height
        width:800
        z:2
        DownloadHistoryView{
            id:downloadHistoryView
            anchors.fill:parent
            m_width:Math.min(parent.width,1000)
            manager:downloadManager
        }

        function toggle() {
            if (drawer2.visible)
                drawer2.close()
            else
                drawer2.open()
        }
    }

    //setting
    Drawer {
        id: drawer
        edge: Qt.RightEdge
        height: window.height
        z:2

        Control {
            padding: 16
            contentItem: ColumnLayout {
                spacing:10
                Label {
                    Layout.alignment: Qt.AlignHCenter
                    text: qsTr("Settings")
                    font.capitalization: Font.AllUppercase
                }
                MenuSeparator {}
                Text{
                    text:"广告拦截"
                }
                MySwitch {
                    id: adBlockSwitch
                    text: "AdBlock";
                    checked: false;

                    onCheckedChanged: currentWebView.reload();
                }
                Text{
                    Layout.topMargin:20
                    text:"UA切换"
                }
                Column {
                    Layout.topMargin:10
                    spacing: 15
                    id:column
                    MyRadioButton {
                        text: "chorme"
                        checked: true
                        checkedColor: "#727CF5"
                        onClicked:{
                            if(checked){
                                column.update(1)
                            }

                        }
                    }

                    MyRadioButton {
                        text: "Opera"
                        checkedColor: "#727CF5"
                        onClicked:{
                            if(checked){
                                column.update(2)
                            }
                        }
                    }

                    MyRadioButton {
                        text: "Safari"
                        checkedColor: "#727CF5"
                        onClicked:{
                            if(checked){
                                column.update(3)
                            }
                        }
                    }
                    MyRadioButton {
                        text: "Internet Explore"
                        checkedColor: "#727CF5"
                        onClicked:{
                            if(checked){
                                column.update(4)
                            }
                        }
                    }
                    MyRadioButton {
                        text: "爬虫机器人"
                        checkedColor: "#727CF5"
                        onClicked:{
                            if(checked){
                                column.update(5)
                            }
                        }
                    }

                    function update(index){
                        let ua=""
                        switch(index){
                        case 1:
                            ua="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
                            break;
                        case 2:
                            ua="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36 OPR/38.0.2220.41"
                            break;
                        case 3:
                            ua="Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1"
                            break;
                        case 4:
                            ua="Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0)"
                            break;
                        case 5:
                            ua="Googlebot/2.1 (+http://www.google.com/bot.html)"
                            break;
                        default:
                            ua="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
                        }

                        console.log("ua update",ua)
                        webProfile.httpUserAgent=ua
                        currentWebView.reload();

                    }
                }

            }
        }

        function toggle() {
            if (drawer.visible)
                drawer.close()
            else
                drawer.open()
        }
    }

    //history
    Drawer{
        id:drawer3
        edge: Qt.RightEdge
        height: window.height
        width:800
        z:2
        HistoryView{
            id:historyView
            anchors.fill:parent
        }

        onOpenedChanged: {
            historyView.getList()
            console.log("drawer open")
        }

        function toggle() {
            if (drawer3.visible)
                drawer3.close()
            else
                drawer3.open()
        }
    }

    //bookmark
    Drawer{
        id:drawer4
        edge: Qt.RightEdge
        height: window.height
        width:800
        z:2
        BookmarkView{
            id:bookmarkView
            anchors.fill:parent
        }

        onOpenedChanged: {
            bookmarkView.getList()
            console.log("drawer open")
        }

        function toggle() {
            if (drawer4.visible)
                drawer4.close()
            else
                drawer4.open()
        }
    }

}
